/*
 * Copyright (c) 2012 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/shm.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/msg.h>
#pragma pack(1)
#define mem_size 1024*1024*200UL
#define MKEY_PATH  "/usr/bin"
#define QUEUE_PATH "/usr/lib"
#define msg_type     886

static int KEY_ID_WRIRE[] = {
    0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38
};
static int MSG_QUEUE_KEY_ID_READ[] = {
    0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
};

struct msg{
    unsigned int len;
    unsigned int offset ;
};
struct msg_que{
    long mtype;
    struct msg block;
};

char *share_mem=NULL ;
int shmid , queId;

void Get_CtrlC_handler(int sig);
void queue_init(int *id);
void *share_mem_init(int *id);

int main()
{
	signal(SIGINT, Get_CtrlC_handler);
	struct msg_que writebuf ;
	memset(&writebuf, 0, sizeof(struct msg_que));
	writebuf.mtype = msg_type ;

	queue_init(&queId);
	share_mem = share_mem_init(&shmid);
	if(share_mem == NULL) {
		return -1;
	}

	unsigned int offset=0x1000 ;
	unsigned int len = 0x100 ;
	for(int i=0; i<len; i++)
	{
		*(share_mem+offset+i) = i+1 ;
	}

	writebuf.block.len = len;
	writebuf.block.offset = offset ;
	while(1)
	{
		msgsnd(queId, &writebuf, sizeof(writebuf.block), 0);
		sleep(5) ;
	}

    return 0;
}

void queue_init(int *id)
{
	key_t tmp_key = ftok(QUEUE_PATH, MSG_QUEUE_KEY_ID_READ[0]);
	*id = msgget(tmp_key, IPC_CREAT|0666);
	if(*id<0)
		printf("get queue failed\n");
	printf("msgId=%d\n", *id);
}

void *share_mem_init(int *id)
{
	key_t tmp_key = ftok(MKEY_PATH, KEY_ID_WRIRE[0]);
	*id = shmget(tmp_key, mem_size, IPC_CREAT | 0666);
	if(*id < 0) {
		printf("mem share failed\n");
		return NULL;
	}
	void *share_mem = shmat(*id, NULL, 0); //0 = r/w ;
	if(share_mem == NULL) {
		printf("mem failed\n");
		return NULL;
	}
	printf("share_mem=%p, shmid=%d\n", share_mem, *id);
	return share_mem ;
}

void Get_CtrlC_handler(int sig)
{
	shmdt(share_mem);
	exit(0);
}
